<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RichTextEditor from '@/components/RichTextEditor.vue'
import {
  fetchCommentPage,
  getCommentById,
  createComment,
  updateComment,
  deleteComment,
  deleteCommentBatch,
} from '@/api/comment'

const loading = ref(false)
const pageNo = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])

const query = reactive({ uname: '', mname: '', minScore: '' })

const multipleSelection = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('新增评论')
const isEdit = ref(false)
const formRef = ref()
const form = reactive({
  id: null,
  uid: null,
  uname: '',
  mid: null,
  mname: '',
  tid: null,
  score: 0,
  cotime: new Date(),
  content: '',
})

const rules = {
  uname: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  mname: [{ required: true, message: '请输入电影名', trigger: 'blur' }],
  score: [
    { required: true, message: '请输入评分', trigger: 'blur' },
    { validator: (_r, v, cb) => (v >= 0 && v <= 10 ? cb() : cb(new Error('评分范围0-10'))), trigger: 'blur' },
  ],
  cotime: [{ required: true, message: '请选择评论时间', trigger: 'change' }],
  content: [{ required: true, message: '请输入评论内容', trigger: 'blur' }],
}

function loadData() {
  loading.value = true
  fetchCommentPage({
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    uname: query.uname || undefined,
    mname: query.mname || undefined,
    minScore: query.minScore ? Number(query.minScore) : undefined,
  })
    .then((res) => {
      if (String(res.code) === '200') {
        list.value = res.data?.records || []
        total.value = res.data?.total || 0
      } else {
        ElMessage.error(res.msg || '查询失败')
      }
    })
    .finally(() => {
      loading.value = false
    })
}

function handleQuery() {
  pageNo.value = 1
  loadData()
}

function resetQuery() {
  query.uname = ''
  query.mname = ''
  query.minScore = ''
  handleQuery()
}

function handleSelectionChange(rows) {
  multipleSelection.value = rows || []
}

function handleAdd() {
  dialogTitle.value = '新增评论'
  isEdit.value = false
  Object.assign(form, {
    id: null,
    uid: null,
    uname: '',
    mid: null,
    mname: '',
    tid: null,
    score: 0,
    cotime: new Date(),
    content: '',
  })
  dialogVisible.value = true
}

async function handleEdit(row) {
  dialogTitle.value = '编辑评论'
  isEdit.value = true
  try {
    const res = await getCommentById(row.id)
    if (String(res.code) === '200') {
      Object.assign(form, res.data || row)
    } else {
      Object.assign(form, row)
      ElMessage.warning(res.msg || '获取详情失败，已使用列表数据')
    }
  } catch (e) {
    Object.assign(form, row)
  }
  dialogVisible.value = true
}

function submitForm() {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const payload = { ...form }
      const api = isEdit.value ? updateComment : createComment
      const res = await api(payload)
      if (String(res.code) === '200') {
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
        dialogVisible.value = false
        loadData()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (e) {}
  })
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确认删除评论 #${row.id}（${row.uname} - ${row.mname}）吗？`, '提示', { type: 'warning' })
    const res = await deleteComment(row.id)
    if (String(res.code) === '200') {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (e) {}
}

async function handleBatchDelete() {
  const ids = multipleSelection.value.map((i) => i.id)
  if (!ids.length) return ElMessage.warning('请先选择要删除的记录')
  try {
    await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 条评论吗？`, '提示', { type: 'warning' })
    const res = await deleteCommentBatch(ids)
    if (String(res.code) === '200') {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) {}
}

function handleSizeChange(size) {
  pageSize.value = size
  pageNo.value = 1
  loadData()
}

function handleCurrentChange(page) {
  pageNo.value = page
  loadData()
}

function htmlToText(html) {
  if (!html) return ''
  const div = document.createElement('div')
  div.innerHTML = html
  return (div.textContent || div.innerText || '').trim()
}

function formatDate(d) {
  if (!d) return '-'
  try {
    const date = typeof d === 'string' || typeof d === 'number' ? new Date(d) : d
    return date.toLocaleString()
  } catch (e) {
    return String(d)
  }
}

onMounted(loadData)
</script>

<template>
  <div class="page">
    <div class="page-header">
      <div class="title">评论管理</div>
      <div class="actions">
        <!-- <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增评论
        </el-button> -->
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <el-card class="card" shadow="never">
      <el-form :inline="true" :model="query" class="query-form">
        <el-form-item label="用户名">
          <el-input v-model="query.uname" placeholder="支持模糊查询" clearable />
        </el-form-item>
        <el-form-item label="电影名">
          <el-input v-model="query.mname" placeholder="支持模糊查询" clearable />
        </el-form-item>
        <el-form-item label="最低评分">
          <el-input v-model="query.minScore" placeholder="0-10" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="card" shadow="never">
      <el-table
        :data="list"
        v-loading="loading"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="uname" label="用户名" min-width="140" />
        <el-table-column prop="mname" label="电影名" min-width="180" />
        <el-table-column prop="tid" label="订单ID" width="100" />
        <el-table-column prop="score" label="评分" width="100" />
        <el-table-column prop="cotime" label="评论时间" min-width="180">
          <template #default="{ row }">
            {{ formatDate(row.cotime) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" min-width="220">
          <template #default="{ row }">
            <span class="desc">{{ htmlToText(row.content) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="pageNo"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="720px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="112px">
        <el-form-item label="用户ID">
          <el-input-number v-model="form.uid" :min="0" :step="1" controls-position="right" style="width: 220px" />
        </el-form-item>
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="form.uname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="电影ID">
          <el-input-number v-model="form.mid" :min="0" :step="1" controls-position="right" style="width: 220px" />
        </el-form-item>
        <el-form-item label="电影名" prop="mname">
          <el-input v-model="form.mname" placeholder="请输入电影名" />
        </el-form-item>
        <el-form-item label="订单ID">
          <el-input-number v-model="form.tid" :min="0" :step="1" controls-position="right" style="width: 220px" />
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-input-number v-model="form.score" :min="0" :max="10" :step="0.1" :precision="1" controls-position="right" style="width: 220px" />
        </el-form-item>
        <el-form-item label="评论时间" prop="cotime">
          <el-date-picker v-model="form.cotime" type="datetime" placeholder="选择日期时间" style="width: 240px" />
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <RichTextEditor v-model="form.content" height="240px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page {
  padding: 16px;
}
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.title {
  font-size: 18px;
  font-weight: 600;
}
.card {
  margin-bottom: 12px;
}
.query-form :deep(.el-form-item) {
  margin-right: 12px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
.desc {
  display: inline-block;
  max-width: 380px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>